package com.st.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.st.entity.User;

@WebFilter(filterName="userFilter", urlPatterns= {"*.do", "*.jsp"})
public class F03_UserFilter implements Filter {

	public void destroy() {
		System.out.println("Filter.destroy");
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		System.out.println("Filter.doFilter");
		
		// 对客户端的请求进行过滤操作. 
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		
		/*
		 * 当路径是 login.jsp, index.jsp, user.do?action=login 
		 */
		// 判断路径 
		String uri = req.getRequestURI();
		if (uri.endsWith("login.jsp") || uri.endsWith("index.jsp") || uri.endsWith("testSession.jsp")) {
			// 放行
			chain.doFilter(request, response);
			
			return ;
		} else if (uri.endsWith("user.do")) {
			// action参数, 还要是login才能放行
			String action = req.getParameter("action");
			
			if ("login".equals(action)) {
				chain.doFilter(request, response);
				return ;
			}
		}
		
		// 获取Session
		HttpSession session = req.getSession();
		// 获取登录用户
		User user = (User) session.getAttribute("user");
		
		if (user != null) {
			// 放行  (实际上是执行在Filter链上的其它的过滤器.)
			chain.doFilter(request, response);
		} else {
			// 拦截
			// 跳转到登录页面
			resp.sendRedirect("login.jsp");
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("Filter.init");
	}
}
